Scroll Progress Bar

While Loop

The while-loop repeatedly executes the code inside its body until the specified condition becomes false. It's a porful control structure for handling repetitive tasks in C language.


#include <stdio.h>

int main() {
    // Declare and initialize a variable for iteration
    int count = 1;

    // Continue the loop as long as the condition (count <= 5) is true
    while (count <= 5) {
        // Print the current iteration number
        printf("Iteration: %d\n", count);

        // Increment the count variable by 1 to move to the next iteration
        count = count + 1;
    }

    // The loop ends here when the condition (count <= 5) becomes false
    return 0;
}
Explanation:
  • Declare and initialize a variable called count to store the current iteration number. set it to 1 to start the loop from the first iteration.
  • The while loop is used to repeat a block of code as long as the condition count <= 5 is true.
  • In each iteration, the code inside the loop body is executed. It prints the current value of count using printf() to show the iteration number.
  • After printing the current iteration number, increment the value of count by 1 using count = count + 1; to move to the next iteration.
  • The loop continues to execute the code inside the loop body as long as the condition count <= 5 remains true.
  • Once the condition count <= 5 becomes false (i.e., when count becomes 6), the loop terminates, and the program moves to the next statement after the while loop.
  • In this example, the while loop will execute 5 iterations, printing the numbers 1 to 5.
Sample Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

What is the purpose of a while-loop in C?


Iteration

What is the condition in a while-loop evaluated as?


Boolean

What keyword is used to exit a while-loop prematurely?


Break